package com.example.service.impl;

import com.example.info.LoginInfo;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.pojo.PageResult;
import com.example.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //分页查询
    public PageResult page(Integer page, Integer pageSize){
        //设置分页参数
        PageHelper.startPage(page, pageSize);

        //执行查询
        List<User> list = userMapper.findAll();
        Page<User> p = (Page<User>) list;

        //封装分页结果
        return new PageResult(p.getTotal(), p.getResult());
    }

    //新增
    public void save(User user){
        user.setUserType(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        //重置自增主键
        //userMapper.resetAutoIncrement();
    }

    //删除
    public void deleteById(Integer userID){
        userMapper.deleteById(userID);
        //重置自增主键
        //userMapper.resetAutoIncrement();
        //将userID大于指定值的记录的userID减1
        //userMapper.decrementUserIDAfter(userID);
    }

    //查询
    public User getById(Integer userID){
        return userMapper.getById(userID);
    }

    //修改
    public void update(User user){
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    //获取所有用户名
    public List<String> getUsername(){
        return userMapper.getUserName();
    }

    //根据用户名获得密码
    public LoginInfo getPasswordByUserName(String userName){
        return userMapper.getPasswordByUserName(userName);
    }
}
